<template>
  <VZPanel title="售后索赔日期数量分布" simple iconText="mdi-chart-pie">
    <div style="margin:-16px">
      <v-card>
        <v-row>
          <v-col cols="3">
            <v-autocomplete
                    v-model="selectedReferred"
                    :items="referredItems"
                    item-text="text"
                    item-value="id"
                    label="搜索零件简称"
                    outlined
                    dense
                    clearable
                    :filter="customFilter"
                    :loading="loading"
                    multiple 
            ></v-autocomplete>
          </v-col>
          <v-col cols="2.5">
            <v-autocomplete
                    v-model="selectedMaterial"
                    :items="materialItems"
                    item-text="text"
                    item-value="id"
                    label="搜索产品"
                    outlined
                    dense
                    clearable
                    :filter="customFilter"
                    :loading="loading"
            ></v-autocomplete>
          </v-col>
          <v-col cols="2">
            <v-select
                    v-model="startYear"
                    :items="yearOptions"
                    label="开始年份"
                    outlined
                    dense
                    :menu-props="{ bottom: true, offsetY: true }"
            ></v-select>
          </v-col>
          <v-col cols="2">
            <v-select
                    v-model="endYear"
                    :items="yearOptions"
                    label="结束年份"
                    outlined
                    dense
                    :menu-props="{ bottom: true, offsetY: true }"
            ></v-select>
          </v-col>
          <v-spacer></v-spacer>
          <v-col cols="auto" class="d-flex align-center">
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  icon
                  color="success"
                  @click="exportToCSV"
                  :disabled="loading"
                  class="mr-2"
                  v-bind="attrs"
                  v-on="on"
                  style="width: 36px; height: 36px"
                >
                  <v-icon size="24">mdi-file-excel</v-icon>
                </v-btn>
              </template>
              <span>导出Excel</span>
            </v-tooltip>
            <v-tooltip bottom>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  icon
                  color="primary"
                  @click="exportChart"
                  :disabled="loading"
                  v-bind="attrs"
                  v-on="on"
                  style="width: 36px; height: 36px"
                >
                  <v-icon size="24">mdi-image</v-icon>
                </v-btn>
              </template>
              <span>导出图片</span>
            </v-tooltip>
          </v-col>
        </v-row>
        <div ref="target" style="width:100%;height:450px"></div>
        <v-data-table
                :headers="tableHeaders"
                :items="tableItems"
                :items-per-page="-1"
                class="elevation-1"
                hide-default-footer
                dense
        >
          <template v-slot:item.month="{ item }">
            {{ item.month }}月
          </template>
          <template v-slot:item="{ item }">
            <tr :class="item.month === '合计' ? 'font-weight-bold' : ''">
              <td>{{ item.month === '合计' ? item.month : item.month + '月' }}</td>
              <td v-for="year in years" :key="year" class="text-center">{{ item[year] }}</td>
            </tr>
          </template>
        </v-data-table>
      </v-card>
    </div>
  </VZPanel>
</template>

<script>
  export default {
    data() {
      return {
        nameList: [],
        numList: [],
        materialSql: "SELECT id,CONCAT(name,'   ',ASSEMBLY_CODE) name FROM tb_standard_assembly_product WHERE MARK_FOR_DELETE = 0",
        referredSql: "SELECT c.id,CONCAT(c.SIMPLE_CALL,'   ',c.CODE) name FROM tt_sale_record_qms a  " +
                "LEFT JOIN tb_standard_assembly_product b ON a.MATERIAL_ID = b.ID " +
                "LEFT JOIN tb_standard_assembly_product_referred c ON c.id = b.REFERRED_ID " +
                "WHERE c.SIMPLE_CALL IS NOT NULL  " +
                "GROUP BY c.ID ",
        materialItems: [],
        referredItems: [],
        searchMaterial: '',
        selectedMaterial: '',
        selectedReferred: [], // 修改为数组
        yearOptions: [], // 年份选项
        startYear: '',
        endYear: '',
        loading: true,
        yearData: {},  // 存储各年份数据
        materialIds: [], // 存储要查询的产品ID数组
        tableHeaders: [], // 表格表头
        tableItems: [], // 表格数据
      }
    },
    computed: {
      years() {
        if (!this.startYear || !this.endYear) return [];
        const start = parseInt(this.startYear);
        const end = parseInt(this.endYear);
        return Array.from({length: end - start + 1}, (_, i) => String(start + i));
      }
    },
    methods: {
      run() {
        if (!this.chartTarget) {
          this.chartTarget = this.$echarts.init(this.$refs.target);
        }

        // 先清空图表
        this.chartTarget.clear();

        let option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: (params) => {
              let result = params[0].axisValue + '月<br/>';
              params.forEach(param => {
                result += `${param.seriesName}年: ${param.value}个<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: this.years,
            right: "center"
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          toolbox: {
            show: false,
            feature: {
              dataView: {
                readOnly: false
              },
              magicType: {
                type: ["line", "stack"]
              },
              restore: {},
              saveAsImage: {}
            }
          },
          xAxis: [
            {
              type: 'category',
              axisTick: {
                show: false
              },
              data: this.nameList
            },
          ],
          yAxis: [
            {
              type: 'value',
              name: '数量',
              axisLabel: {
                formatter: '{value} 个'
              }
            }
          ],
          series: this.years.map((year, index) => ({
            name: year,
            type: 'line',
            data: this.yearData[year] || [],
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#88aecc',
                    fontSize: 12
                  }
                }
              }
            },
            tooltip: {
              valueFormatter: function (value) {
                return value + '个';
              }
            }
          }))
        }
        this.chartTarget.setOption(option);
        let _this = this;
        this.chartTarget.on('click', function (params) {
          // 获取点击的月份
          const month = params.name;  // 格式是'01', '02'等
          // 获取图例名称，即年份
          const year = params.seriesName;
          
          // 构建完整的年月字符串
          const yearMonth = `${year}-${month}`;
          
          // 计算该月的第一天
          const firstDay = `${year}-${month}-01`;
          
          // 计算该月的最后一天
          let lastDayDate = new Date(parseInt(year), parseInt(month), 0);
          const lastDay = lastDayDate.getFullYear() + '-' + 
                         String(lastDayDate.getMonth() + 1).padStart(2, '0') + '-' + 
                         String(lastDayDate.getDate()).padStart(2, '0');
          
          _this.$emit('toPage', 'v4a964e28354dd5945af2da28ad', {
            material_id: _this.materialIds.join(','),
            back_month_btime: firstDay,
            back_month_etime: lastDay
          });
        });
        // 更新表格数据
        this.updateTableData();
      },
      search_data() {
        if (this.materialIds.length === 0) {
          return;
        }
        let _this = this;
        this.yearData = {};  // 清空之前的数据
        this.loading = true; // 添加loading状态

        // 创建包含所有月份的数组
        let allMonths = Array.from({length: 12}, (_, i) => String(i + 1).padStart(2, '0'));
        this.nameList = allMonths;

        // 为每个年份获取数据
        let completedRequests = 0;
        this.years.forEach(year => {
          let params = {
            "SQL": `SELECT DATE_FORMAT(back_month, '%m') AS name,COUNT(*) AS num
                    FROM tt_sale_record_qms a
                    WHERE a.MATERIAL_ID IN (${this.materialIds.join(',')})
                    AND DATE_FORMAT(back_month, '%Y') = '${year}'
                    GROUP BY DATE_FORMAT(back_month, '%m')
                    ORDER BY name;`
          };

          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success) {
                let monthMap = {};
                // 初始化月份映射
                allMonths.forEach(month => {
                  monthMap[month] = 0;
                });
                // 更新实际数据
                res.rows.forEach((item) => {
                  monthMap[item.name] = item.num;
                });
                // 存储该年份的数据
                _this.yearData[year] = allMonths.map(month => monthMap[month]);
                completedRequests++;

                // 当所有年份数据都获取完成后，更新图表
                if (completedRequests === _this.years.length) {
                  _this.run();
                  _this.loading = false;
                }
              } else {
                completedRequests++;
                if (completedRequests === _this.years.length) {
                  _this.loading = false;
                }
              }
            },
          });
        });
      },
      // 获取零件简称信息
      loadReferredData() {
        let _this = this;
        _this.referredItems = [];
        let params = {"SQL": this.referredSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let referredList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                referredList.push(map);
              })
              _this.referredItems = referredList;
              // 设置默认选中第一个零件简称
              if (_this.referredItems.length > 0) {
                _this.selectedReferred = [_this.referredItems[0].id]; // 修改为数组
                _this.loadMaterialIdsByReferred().then(() => {
                  if (_this.materialIds.length > 0) {
                    _this.search_data();
                  }
                });
              }
            }
          },
        })
      },
      // 获取产品信息
      loadMaterialData() {
        let _this = this;
        _this.materialItems = [];
        let params = {"SQL": this.materialSql};
        app.utils.ajaxRequest({
          hideMsg: true,
          hideMask: true,
          url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
          params: {
            functionParam: JSON.stringify(params)
          },
          callBack(res) {
            if (res.success && res.rows.length > 0) {
              let dataList = res.rows;
              let materialList = [];
              dataList.forEach((item) => {
                let map = {};
                map.text = item.name;
                map.id = item.id;
                materialList.push(map);
              })
              _this.materialItems = materialList;
            }
            _this.loading = false;
          },
        })
      },
      // 根据零件简称获取产品ID列表
      loadMaterialIdsByReferred() {
        if (!this.selectedReferred || this.selectedReferred.length === 0) {
          this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
          return Promise.resolve();
        }

        let _this = this;
        let params = {
          "SQL": `SELECT DISTINCT a.id
                  FROM tb_standard_assembly_product a
                  WHERE a.MARK_FOR_DELETE = 0
                  AND a.REFERRED_ID IN (${this.selectedReferred.join(',')})` // 修改为IN查询
        };

        return new Promise((resolve) => {
          app.utils.ajaxRequest({
            hideMsg: true,
            hideMask: true,
            url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
            params: {
              functionParam: JSON.stringify(params)
            },
            callBack(res) {
              if (res.success && res.rows.length > 0) {
                _this.materialIds = res.rows.map(item => item.id);
              } else {
                _this.materialIds = [];
              }
              resolve();
            },
          });
        });
      },
      // 初始化年份选项
      initYearOptions() {
        const currentYear = new Date().getFullYear();
        const startYear = 2020; // 设置起始年份
        const endYear = currentYear + 1; // 设置结束年份为当前年份+1
        this.yearOptions = Array.from({length: endYear - startYear + 1}, (_, i) => String(startYear + i));
        // 设置默认值
        this.startYear = String(startYear);
        this.endYear = String(currentYear);
      },
      reset() {
        this.searchMaterial = '';
        this.selectedMaterial = '';
        this.selectedReferred = []; // 修改为数组
        this.startYear = '';
        this.endYear = '';
        this.search_data();
      },
      customFilter(item, queryText, itemText) {
        const textOne = itemText.toLowerCase();
        const searchText = queryText.toLowerCase();

        return textOne.indexOf(searchText) > -1;
      },
      // 更新表格数据
      updateTableData() {
        // 生成表头
        this.tableHeaders = [
          { text: '月份', value: 'month', width: '100px' },
          ...this.years.map(year => ({
            text: year,
            value: year,
            align: 'center'
          }))
        ];

        // 生成表格数据
        this.tableItems = Array.from({length: 12}, (_, i) => {
          const month = String(i + 1).padStart(2, '0');
          const item = { month };
          this.years.forEach(year => {
            item[year] = this.yearData[year] ? this.yearData[year][i] : 0;
          });
          return item;
        });

        // 添加汇总行
        const totalRow = { month: '合计' };
        this.years.forEach(year => {
          totalRow[year] = this.tableItems.reduce((sum, item) => sum + item[year], 0);
        });
        this.tableItems.push(totalRow);
      },
      // 导出CSV
      exportToCSV() {
        try {
          // 准备CSV数据
          let csvContent = "\ufeff"; // 添加BOM头
          csvContent += "售后索赔日期数量分布\n\n";
          
          // 添加表头
          const headers = ['月份', ...this.years];
          csvContent += headers.join(',') + '\n';
          
          // 添加数据行
          this.tableItems.forEach(item => {
            const row = [item.month === '合计' ? '合计' : item.month + '月'];
            this.years.forEach(year => {
              row.push(item[year]);
            });
            csvContent += row.join(',') + '\n';
          });
          
          // 创建Blob对象，指定编码为UTF-8
          const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = '售后索赔日期数量分布.csv';
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          
        } catch (error) {
          console.error('导出CSV失败:', error);
          app.utils.showMessage('导出CSV失败，请稍后重试');
        }
      },
      // 导出图表为图片
      exportChart() {
        try {
          if (!this.chartTarget) {
            app.utils.showMessage('图表未初始化，请稍后重试');
            return;
          }
          
          // 获取图表的base64图片数据
          const imageUrl = this.chartTarget.getDataURL({
            type: 'png',
            pixelRatio: 2, // 提高图片质量
            backgroundColor: '#fff',
            excludeComponents: ['toolbox'] // 排除工具箱组件
          });
          
          // 创建下载链接
          const link = document.createElement('a');
          link.download = '售后索赔日期数量分布图表.png';
          link.href = imageUrl;
          
          // 触发下载
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          
        } catch (error) {
          console.error('导出图表失败:', error);
          app.utils.showMessage('导出图表失败，请稍后重试');
        }
      },
    },
    watch: {
      selectedMaterial() {
        if (this.selectedMaterial) {
          // 如果选择了产品，清空简称选择
          this.selectedReferred = []; // 修改为数组
          this.materialIds = [this.selectedMaterial];
          this.search_data();
        }
      },
      async selectedReferred() {
        if (this.selectedReferred && this.selectedReferred.length > 0) {
          // 如果选择了简称，清空产品选择
          this.selectedMaterial = '';
          // 等待获取产品ID列表完成
          await this.loadMaterialIdsByReferred();
          if (this.materialIds.length > 0) {
            this.search_data();
          }
        } else {
          // 如果清空了简称，且没有选择产品，清空materialIds
          if (!this.selectedMaterial) {
            this.materialIds = [];
          }
        }
      },
      startYear() {
        if (this.materialIds.length > 0) {
          this.search_data();
        }
      },
      endYear() {
        if (this.materialIds.length > 0) {
          this.search_data();
        }
      }
    },
    created() {
      this.initYearOptions();
      this.loadMaterialData();
      this.loadReferredData();
      setTimeout(() => {
        this.search_data();
      }, 1000);
    },
    mounted() {
      window.onresize = () => {
        this.chartTarget.resize();
      }
    },
  }
</script>

<style scoped>
.v-btn {
  text-transform: none;
}
</style>
